//
//  MapViewController.m
//  Edumap
//
//  Created by 刘建峰 on 16/7/18.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MapViewController.h"
#import "NavPointAnnotation.h"
#import "InformationDetailsViewController.h"

@interface MapViewController ()
<UITextFieldDelegate,UIAlertViewDelegate,CLLocationManagerDelegate> {
    NSString *AAC001;
}
@property (weak, nonatomic) IBOutlet UIView *navView;


@property (weak, nonatomic) IBOutlet UIView *mapBackView;
@property (weak, nonatomic) IBOutlet UIView *addressView;
@property (weak, nonatomic) IBOutlet UIView *navButtonView;
@property (weak, nonatomic) IBOutlet UIView *callView;


@property (weak, nonatomic) IBOutlet UIView *teachView;
@property(nonatomic,assign)BOOL firstLoc;
@property(nonatomic,strong)NSMutableArray * poorArray;
@property(nonatomic,strong)NSMutableArray * poorPointArray;
@property(nonatomic,strong)NSMutableArray * currentpoorArray;
@property(nonatomic,strong)NSString * schoolType;

@property (weak, nonatomic) IBOutlet UILabel *schoolName;
@property (weak, nonatomic) IBOutlet UILabel *schoolAddress;

@property (nonatomic, strong) NavPointAnnotation *endAnnotation;
@property(nonatomic,assign)BOOL isInit;//是否第一次初始化
@property(nonatomic,assign)BOOL isDetail;//是否从学校详情返回
@property(nonatomic,strong)CLLocationManager * locationManger;


@end

@implementation MapViewController

- (void)viewDidDisappear:(BOOL)animated{
    [self clearMapView];
    _isInit = NO;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    if ([Common getLoginStatus]) {
//        _noticeNum.hidden = YES;
//        [self getnoticeNum];
//    } else {
//        _noticeNum.hidden = YES;
//    }
    if (_isInit==NO &&_isDetail ==NO) {
         [self initNavgationMap];
    }
    [self startLocation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _poorArray = [NSMutableArray array];
    _poorPointArray = [NSMutableArray array];
    _currentpoorArray = [NSMutableArray array];
    _isInit = YES;
    [self initNavgationMap];
    [self initViewLayout];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.mapBackView];
    [self adaptiveViewLayout:self.callView];
    [self adaptiveViewLayout:self.teachView];
    [self adaptiveViewLayout:self.addressView];
    [self adaptiveViewLayout:self.navButtonView];
    
    _mapBackView.frame = CGRectMake(0, 64*VerticalRatio(), 320*VerticalRatio(), 504*VerticalRatio());
    _addressView.frame = CGRectMake(0, (504-58)*VerticalRatio(), 320*VerticalRatio(), 58*VerticalRatio());
    _navButtonView.frame = CGRectMake(245*VerticalRatio(), CGRectGetHeight(_mapBackView.frame)-78*VerticalRatio(), 58*VerticalRatio(), 58*VerticalRatio());
    _navButtonView.layer.cornerRadius = 29*VerticalRatio();
    _callView.layer.cornerRadius = 29*VerticalRatio();
    _teachView.layer.cornerRadius = 25*VerticalRatio();

    [_mapBackView insertSubview:_navButtonView aboveSubview:_addressView];
    [_mapBackView insertSubview:_callView aboveSubview:_addressView];

}

- (IBAction)back:(id)sender {
    [self backBtn];
}
#pragma mark - 搜索
- (IBAction)search:(id)sender {
}

#pragma mark ==== UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self hideKeyBoard];
//    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"MapStoryboard" bundle:nil];
//    SearchViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Search"];
//    page.serachStr = _textField.text;
//    [[Common getNavigation] pushViewController:page];
    return YES;
}

#pragma mark  地图导航实例化--=========================================
- (void)initNavgationMap{
    
    [self initMapView];
    
    [self initNaviManager];
    
    [self initIFlySpeech];
    //导航控制器
    [self initNaviViewController];
    
    [self configMapView];
    
}
- (void)configMapView
{
     _firstLoc = YES;
    self.mapView.frame = flexibleFrame(CGRectMake(0, 0, 320, 534), NO);
    [_mapBackView insertSubview:self.mapView atIndex:0];
    self.mapView.delegate = self;
    self.mapView.showsCompass= NO;
    self.mapView.showsScale = NO;
    self.mapView.showsUserLocation = YES;
   
}
#pragma mark === 改变学校类型
- (IBAction)changeType:(UIButton*)sender {
    _schoolType = @"05";
    [self.mapView removeAnnotations:self.poorPointArray];
    [self.poorPointArray removeAllObjects];
    [_currentpoorArray removeAllObjects];
    for(NSDictionary * dic in _poorArray) {
        NSString * type = [NSString stringWithFormat:@"%@",dic[@"TYPE"]];
        if ([type isEqualToString:@"01"] || [type isEqualToString:@"02"] || [type isEqualToString:@"03"] || [type isEqualToString:@"04"]) {
            [_currentpoorArray addObject:dic];
        }
    }
    
    for (int i=0; i<self.currentpoorArray.count; i++) {
      NSDictionary *  dic = self.currentpoorArray[i];
        //终点
        NavPointAnnotation * Annotation = [[NavPointAnnotation alloc] init];
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([dic[@"AAT001"] floatValue], [dic[@"AAG001"] floatValue]);
        [Annotation setCoordinate:coordinate];
        Annotation.title        = [NSString stringWithFormat:@"%d",i];
        [self.mapView addAnnotation:Annotation];
        [self.poorPointArray addObject:Annotation];
    }

}


#pragma mark  === 档案管理详情
- (IBAction)schoolDetail:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
    InformationDetailsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"InformationDetails"];
    page.AAC001 = AAC001;
    [[Common getNavigation]pushViewController:page];
}


#pragma mark  === 导航

- (IBAction)navHandel:(id)sender {
    NSArray *endPoints;
    self.endAnnotation = [[NavPointAnnotation alloc] init];
    CLLocationCoordinate2D coordinate1 = CLLocationCoordinate2DMake([[[NSUserDefaults standardUserDefaults] objectForKey:@"lat"] floatValue], [[[NSUserDefaults standardUserDefaults] objectForKey:@"lng"] floatValue]);
    [self.endAnnotation setCoordinate:coordinate1];
    endPoints = @[[AMapNaviPoint locationWithLatitude:_endAnnotation.coordinate.latitude
                                            longitude:_endAnnotation.coordinate.longitude]];
    [self.naviManager calculateDriveRouteWithEndPoints:endPoints
                                             wayPoints:nil
                                       drivingStrategy:0];
}

#pragma mark  === 获取附近平困户
- (void)getSchoolPoint{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lat"] forKey:@"lat"];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lng"] forKey:@"lng"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:F_getNearFarmerList withHttpType:@"POST" withTag:F_F_getNearFarmerList];
}

#pragma mark === 获取未读信息数量
- (void)getnoticeNum{

    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msceMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    
    self.shareApi.delegate=self;
//    [self.shareApi  requestOperationWithDic:dic withPath:JY_unreadInformation withHttpType:@"POST" withTag:JY_JY_unreadInformation];
}


#pragma mark -- coreLocation

- (void)startLocation{
    
    // 判断定位操作是否被允许
    
    if([CLLocationManager locationServicesEnabled]) {
        
        _locationManger = [[CLLocationManager alloc] init];
        _locationManger.delegate = self;
        _locationManger.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManger.distanceFilter = 5.0f;
        // 总是授权
        [_locationManger requestAlwaysAuthorization];
        if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8) {
            [_locationManger requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8定位需要）
            [_locationManger requestAlwaysAuthorization];
        }
        [_locationManger startUpdatingLocation];
        
        
    }else {
        
        //提示用户无法进行定位操作
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertView show];
        
    }
    [_locationManger startUpdatingLocation];

}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{

    [_locationManger stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        if (![[NSUserDefaults standardUserDefaults]objectForKey:@"firstLocAgree"]) {
            _firstLoc = YES;
            [[NSUserDefaults standardUserDefaults]setObject:@"firstLocAgree" forKey:@"1"];
        }
    }
}

#pragma mark - MAMapView Delegate

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    
    if (_firstLoc == YES) {
        [self.mapView setCenterCoordinate:userLocation.coordinate];
        _firstLoc = NO;
        [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%f",userLocation.coordinate.latitude] forKey:@"lat"];
        [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%f",userLocation.coordinate.longitude] forKey:@"lng"];
        
        CLLocationCoordinate2D location = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude);
        MACoordinateRegion region = MACoordinateRegionMakeWithDistance(location,5000 ,5000);
        MACoordinateRegion adjustedRegion = [self.mapView regionThatFits:region];
        [self.mapView setRegion:adjustedRegion animated:NO];
        
        [self getSchoolPoint];
    }

}



- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
if ([annotation isKindOfClass:[NavPointAnnotation class]])
    {
        static NSString *annotationIdentifier = @"annotationIdentifier";
        
        MAPinAnnotationView *pointAnnotationView = (MAPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
        if (pointAnnotationView == nil)
        {
            pointAnnotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation
                                                                  reuseIdentifier:annotationIdentifier];
        }
        
        pointAnnotationView.animatesDrop   = NO;
        pointAnnotationView.canShowCallout = NO;//允许交互点击
        pointAnnotationView.draggable      = NO;
        NSInteger index = [annotation.title integerValue];
        NSString *type = [NSString stringWithFormat:@"%@",self.currentpoorArray[index][@"TYPE"]];
        if([type isEqualToString:@"01"]){
            pointAnnotationView.image = [UIImage imageNamed:@"GIS4.png"];
        }else if([type isEqualToString:@"02"]){
            pointAnnotationView.image = [UIImage imageNamed:@"GIS3.png"];
        }
        
        return pointAnnotationView;
    }
    
    return nil;
}


// 当点击annotation view，调用此接口
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    NSInteger index = [view.annotation.title integerValue];
    // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
    if (![view.annotation isKindOfClass:[MAUserLocation class]])
    {
        _addressView.hidden = NO;
        _navButtonView.hidden = NO;
        _callView.hidden = NO;
        NSDictionary * dic = self.currentpoorArray[index];
        _schoolName.text = [NSString stringWithFormat:@"%@",dic[@"NAME"]];
        _schoolAddress.text = [NSString stringWithFormat:@"%@ %@",dic[@"TOWN"],dic[@"COUNTRY"]];
        AAC001 = [NSString stringWithFormat:@"%@",dic[@"AAC001"]];
    }
    
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    if(tag ==F_F_getNearFarmerList ){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            [self.mapView removeAnnotations:self.poorPointArray];
            [self.poorPointArray removeAllObjects];
            [self.poorArray removeAllObjects];
            [self.currentpoorArray removeAllObjects];
            NSArray * array = database[@"data"];
            for (NSDictionary * dic in array) {
                [_poorArray addObject:dic];
                [_currentpoorArray addObject:dic];
            }
            
            for (int i=0; i<self.poorArray.count; i++) {
              NSDictionary * dic = self.poorArray[i];
                //终点
                NavPointAnnotation * Annotation = [[NavPointAnnotation alloc] init];
                CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([dic[@"AAT001"] floatValue], [dic[@"AAG001"] floatValue]);
                [Annotation setCoordinate:coordinate];
                Annotation.title        = [NSString stringWithFormat:@"%d",i];
                [self.mapView addAnnotation:Annotation];
                [self.poorPointArray addObject:Annotation];
            }
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [self dismissWaitDialog];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
